<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { useGetCbBiddingProjectPageList, useSubmitBiddingProject } from '@fl/api/supplier'
import { SearchForm, SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash-es'

import { PROJECE_STATUS_DICT } from './constant'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: '/supplier-pages/pricing-tool/project',
})

const { isPending: submitPending, mutate: submitMuate } = useSubmitBiddingProject()

const { createConfirmModal } = useMessage()

const router = useRouter()

const route = useRoute()

const initialState = {
    categoryId: '',
    projectName: '',
}
const state = ref(cloneDeep(initialState))

const columns: PlusColumn[] = [
    {
        label: '项目名称',
        prop: 'projectName',
    },

]

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}

const tablePage = ref(cloneDeep(initialPage))

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { fixed: 'left', title: '序号', type: 'seq', width: 50 },
        { field: 'projectName', title: '项目名称' },
        { field: 'enterpriseName', title: '招标单位' },
        { field: 'createTime', title: '创建日期' },
        { field: 'publishDate', title: '发布日期' },
        { field: 'endTime', title: '投标截止日期' },
        { field: 'status', formatter(params) {
            return PROJECE_STATUS_DICT[params.cellValue ?? 0]
        }, title: '状态' },
        { slots: { default: 'operate' }, title: '操作', width: 250 },
    ],
    maxHeight: 600,
    rowConfig: {
        keyField: 'projectId',
    },
})

const tableData = ref<any[]>([])

const params = computed(() => {
    return {
        ...state.value,
        page: tablePage.value.currentPage,
        size: tablePage.value.pageSize,
    }
})

const { data, isLoading } = useGetCbBiddingProjectPageList(params)

const loading = computed(() => submitPending.value || isLoading.value)
function reset() {
    state.value = cloneDeep(initialState)
    tablePage.value = cloneDeep(initialPage)
}

function submit(values: any) {
    state.value = cloneDeep(values)
    tablePage.value.currentPage = 1
}

function bidding(row: any) {
    createConfirmModal({
        content: '是否确认投标?',
        onError: () => {
            ElMessage.info('取消投标')
        },
        onSuccess: () => {
            submitMuate(
                {
                    projectId: String(row.projectId),
                },
                {
                    onSuccess: () => {
                        ElMessage.success('投标成功')
                    },
                },
            )
        },
    })
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

function showGroupPrice(id: string) {
    router.push(`${route.path}/${id}`)
}

watchEffect(() => {
    if (data.value) {
        tableData.value = cloneDeep(data.value?.records ?? [])
        tablePage.value.total = data.value?.total ?? 0
    }
})
</script>

<template>
    <ElCard shadow="never"
            mb-20
    >
        <SearchForm v-bind="state"
                    :columns="columns"
                    submit-text="搜索"
                    @reset="reset"
                    @submit="submit"
        />

        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :seq-config="{ startIndex: (tablePage.currentPage - 1) * tablePage.pageSize }"
                     :loading="loading"
                     :data="tableData"
                     @page-change="handlePageChange"
        >
            <template #operate="{ row }">
                <ElButton v-if="dayjs().isBefore(row.endTime || '')"
                          text
                          type="primary"
                          @click="bidding(row)"
                >
                    投标
                </ElButton>

                <ElButton text
                          type="primary"
                          @click="showGroupPrice(row.projectId)"
                >
                    {{ row.status === 1 ? '查看组价' : '查看组价清单' }}
                </ElButton>
            </template>
        </SearchTable>
    </ElCard>
</template>
